package com.codefish.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.codefish.common.PermissionConstants;
import com.codefish.dto.AllPermLeverDTO;
import com.codefish.dto.BaseCommonTypeDto;
import com.codefish.entity.SysBaseCommonEntity;
import com.codefish.mapper.SysBaseCommonDao;
import com.codefish.service.SysBaseCommonService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;


@Service("sysBaseCommonService")
public class SysBaseCommonServiceImpl extends ServiceImpl<SysBaseCommonDao, SysBaseCommonEntity> implements SysBaseCommonService {

    /**
     * 获取公共字段分类
     *
     * @return
     */
    @Override
    public List<BaseCommonTypeDto> getBaseCommonTypeList() {
        List<BaseCommonTypeDto> list = baseMapper.getBaseCommonTypeList();

        // 最后添加 默认值
        BaseCommonTypeDto defaultDto = new BaseCommonTypeDto();
        defaultDto.setType("");
        defaultDto.setTypeName("全部");
        list.add(defaultDto);

        return list;
    }

    /**
     * 条件分页查询
     *
     * @param params
     * @return
     */
    @Override
    public IPage<SysBaseCommonEntity> getPageByParams(Map<String, Object> params) {

        // 分页
        Page<SysBaseCommonEntity> page = new Page<>(
                new Long(params.get("page").toString())
                , new Long(params.get("limit").toString()));

        // 条件构建
        QueryWrapper<SysBaseCommonEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del", 0);
        queryWrapper.orderByAsc("base_common_type");

        if (null != params.get("value") && !params.get("value").toString().isEmpty()) {
            String value = params.get("value").toString();
            queryWrapper.like("base_common_value", value);
        }
        if (null != params.get("type") && !params.get("type").toString().isEmpty()) {
            String type = params.get("type").toString();
            queryWrapper.eq("base_common_type", type);
        }
        IPage<SysBaseCommonEntity> entityIPage = baseMapper.selectPage(page, queryWrapper);

        return entityIPage;
    }

    @Override
    public void updateStatusAndIsDel(Long[] ids) {
        baseMapper.updateStatusAndIsDel(ids);
    }

    /**
     * 删除单个公共字段
     * @param id
     * @return
     */
    @Override
    public boolean deleteOne(Long id) {
        SysBaseCommonEntity deleteEntity = new SysBaseCommonEntity();
        deleteEntity.setId(id);
        deleteEntity.setIsDel(1);

        int deleteCount = baseMapper.updateById(deleteEntity);
        if (deleteCount == 1){
            return true;
        }

        return false;
    }

    /**
     * 查询是否重复
     * @param sysBaseCommon
     * @return
     */
    @Override
    public int selectCount(SysBaseCommonEntity sysBaseCommon) {

        int count = baseMapper.selectCount(new QueryWrapper<SysBaseCommonEntity>()
                .eq("base_common_key", sysBaseCommon.getBaseCommonKey())
                .eq("base_common_type", sysBaseCommon.getBaseCommonType())
                .eq("is_del", 0));

        return count;
    }

    @Override
    public int queryCountByNameAndType(SysBaseCommonEntity sysBaseCommon) {
        return baseMapper.queryCountByNameAndType(sysBaseCommon);
    }

    /**
     * 获取所有权限类型
     * @return
     */
    @Override
    public List<AllPermLeverDTO> getAllPermLever() {

        List<AllPermLeverDTO> retList = new ArrayList<>();

        List<SysBaseCommonEntity> allPermLever = baseMapper.selectList(new QueryWrapper<SysBaseCommonEntity>()
                .select("base_common_key","base_common_value")
                .eq("is_del", 0)
                .eq("status", 1)
                .eq("base_common_type", "permission_lever")
                .isNotNull("base_common_key")
                .isNotNull("base_common_value"));

        if (null != allPermLever && !CollectionUtils.isEmpty(allPermLever)){

            allPermLever.forEach(entity ->{
                AllPermLeverDTO dto = new AllPermLeverDTO();
                if (null != entity.getBaseCommonKey() && !"".equals(entity.getBaseCommonKey())){
                    dto.setBaseCommonKey(entity.getBaseCommonKey());
                }
                if (null != entity.getBaseCommonValue() && !"".equals(entity.getBaseCommonValue())){
                    dto.setBaseCommonValue(entity.getBaseCommonValue());
                }
                retList.add(dto);
            });
        }

        return retList;
    }

    /**
     * 获取所有行业类型
     * @return
     */
    @Override
    public List<BaseCommonTypeDto> getAllCompType() {

        List<BaseCommonTypeDto> reList = new ArrayList<>();

        List<SysBaseCommonEntity> allCompType = baseMapper.selectList(new QueryWrapper<SysBaseCommonEntity>()
                .select("base_common_key","base_common_value")
                .eq("is_del", 0)
                .eq("status", 1)
                .eq("base_common_type", "comp_industry")
                .isNotNull("base_common_key")
                .isNotNull("base_common_value"));

        if (!CollectionUtils.isEmpty(allCompType)){
            allCompType.forEach(entity -> {
                BaseCommonTypeDto dto = new BaseCommonTypeDto();
                if (!StringUtils.isEmpty(entity.getBaseCommonKey())){
                    dto.setType(entity.getBaseCommonKey());
                }

                if (!StringUtils.isEmpty(entity.getBaseCommonValue())){
                    dto.setTypeName(entity.getBaseCommonValue());
                }
                reList.add(dto);
            });
        }

        return reList;
    }

    /**
     * 获取所有行业
     */
    @Override
    public List<BaseCommonTypeDto> getAllCompIndustry(){

        List<BaseCommonTypeDto> reList = new ArrayList<>();

        List<SysBaseCommonEntity> allCompType = baseMapper.selectList(new QueryWrapper<SysBaseCommonEntity>()
                .select("base_common_key","base_common_value")
                .eq("is_del", 0)
                .eq("status", 1)
                .eq("base_common_type", "comp_industry")
                .isNotNull("base_common_key")
                .isNotNull("base_common_value"));

        if (!CollectionUtils.isEmpty(allCompType)){
            allCompType.forEach(entity -> {
                BaseCommonTypeDto dto = new BaseCommonTypeDto();
                if (!StringUtils.isEmpty(entity.getBaseCommonKey())){
                    dto.setType(entity.getBaseCommonKey());
                }

                if (!StringUtils.isEmpty(entity.getBaseCommonValue())){
                    dto.setTypeName(entity.getBaseCommonValue());
                }
                reList.add(dto);
            });
        }

        return reList;
    }

    /**
     * 压缩图片，并等比缩小。
     *
     * @param data    输入图片数据的byte[]。
     * @param width   最大输出宽度，但是最后会根据图片本身比例调整。推荐值800。
     * @param height  最大输出高度，但是最后会根据图片本身比例调整。推荐值600。
     * @param type    指定最后存储的图片类型，支持字符串jpg,png,gif,bmp,jpeg。如果为null，则默认输出jpg格式图片。
     * @param maxSize 指定最大输出图片的容量大小。可以为null表示不指定压缩容量大小。不要小于10000，推荐100000。
     * @return 输出图片数据的byte[]。
     * @throws Exception
     * @author aren
     */
    public static byte[] zipImageToScaledSize(byte[] data, int width, int height, String type, Integer maxSize) throws
            Exception {
        if (data == null) {
            return null;
        }
        if (width <= 0 || height <= 0) {
            width = 800;
            height = 600;
        }
        // 设定输出格式
        String[] supportType = new String[]{"jpg", "png", "bmp", "jpeg", "gif"};
        if (type == null || !ArrayUtils.contains(supportType, type)) {
            type = "jpg";
        }
        int pointedHeight;
        int pointedWidth;
        ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
        BufferedImage bufferedImage = ImageIO.read(inputStream);
        inputStream.close();
        int originalHeight = bufferedImage.getHeight();
        int originalWidth = bufferedImage.getWidth();
        // 设定等比例压缩。
        if ((originalHeight / (double) height) > (originalWidth / (double) width)) {
            pointedHeight = NumberUtils.min(new int[]{height,originalHeight});
            pointedWidth = -1;
        } else {
            pointedHeight = -1;
            pointedWidth = NumberUtils.min(new int[]{width, originalWidth});
        }
        // 压缩图片，此处附上颜色类型BufferedImage.TYPE_INT_RGB。Color.WHITE，可以有效避免png转jpg时图片发红的问题。
        Image newImage = bufferedImage.getScaledInstance(pointedWidth, pointedHeight, Image.SCALE_SMOOTH);
        BufferedImage newBufferedImage = new BufferedImage(newImage.getWidth(null), newImage.getHeight(null),
                BufferedImage.TYPE_INT_RGB);
        newBufferedImage.getGraphics().drawImage(newImage, 0, 0, Color.WHITE, null);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(newBufferedImage, type, byteArrayOutputStream);
        byteArrayOutputStream.close();
        data = byteArrayOutputStream.toByteArray();
        if (maxSize != null && data.length > maxSize) {
            // 设定递归的保险，以免图片质量太差
            if (maxSize < 5000 && (data.length > 10 * maxSize)) {
                maxSize = 5000;
            }
            // 递归压缩
            double scale = Math.max(Math.pow(maxSize / (double) data.length, 0.5), 0.9);
            return zipImageToScaledSize(data, (int) (width * scale), (int) (height * scale), type, maxSize);
        } else {
            return data;

        }
    }

}